#!/usr/bin/env node
const fs = require('fs');
const proj4 = require('proj4');
 
const argvArr = process.argv; //参数
const origialPath = argvArr[2]; // 传入的第一个参数，读取文件
const outPath = argvArr[3]; // 传入的第二个参数，保存文件
 
fs.readFile(origialPath,"utf-8", (err, data) => {
    if(err) {
        return console.error("read error: ", err);
    }
    const originalData = JSON.parse(data);
    const transform = originalData["hc-transform"].default;
    try{
        originalData.features.forEach(feature => {
            feature.geometry.coordinates.forEach(coord => {
                swap(coord, transform);
            })
            feature.properties = {
                name: feature.properties.name
            }
        })
        fs.writeFile(outPath, JSON.stringify(originalData, undefined, 2), 'utf-8', e => {
            if(e) {
                return console.error('write error:', e);
            } else {
                return console.log('write success!')
            }
        })
    } catch(error) {
        console.error('no transform :', error);
    }
})
 
function swap(arr, transform){
    if(Array.isArray(arr[0])){
        arr.forEach(item => {
            swap(item, transform)
        })
    } else {
        const temp = pointToLonlat({x: arr[0], y: arr[1]}, transform);
        arr[0] = temp.lon; // - 3.9;
        arr[1] = temp.lat; // + 0.3;
    }
}
 
 
function pointToLonlat(point, transform) {
    var normalized = {
        x: (
            (
                point.x -
                (transform.jsonmarginX || 0)
            ) / (transform.jsonres || 1) -
            (transform.xpan || 0)
        ) / (transform.scale || 1) +
        (transform.xoffset || 0),
        y: -(
            (
                -point.y + (transform.jsonmarginY || 0)
            ) / (transform.jsonres || 1) -
            (transform.ypan || 0)
        ) / (transform.scale || 1) +
        (transform.yoffset || 0)
    },
        cosAngle = transform.cosAngle ||
        (transform.rotation && Math.cos(transform.rotation)),
        sinAngle = transform.sinAngle ||
        (transform.rotation && Math.sin(transform.rotation)),
        // Note: Inverted sinAngle to reverse rotation direction
        projected = proj4(transform.crs, 'WGS84', transform.rotation ? {
            x: normalized.x * cosAngle + normalized.y * -sinAngle,
            y: normalized.x * sinAngle + normalized.y * cosAngle
        } : normalized);
    return { lat: projected.y, lon: projected.x };
};
